/**
 * Created by spatra on 14-9-8.
 */

define(['jquery', 'app/runloop', 'app/mousemove'], function($, Runloop, Mousemove){

	function toggleBtn(target){
		var currentValue = $(target).attr('disabled');
		$(target).attr('disabled', ! currentValue);
	}

	var theCanvas = null;

	var init = function(canvasIdName){
		theCanvas = document.getElementById(canvasIdName);

		Mousemove.init(theCanvas);

		toggleBtn('#btn-pause');
		toggleBtn('#btn-recover');
		toggleBtn('#btn-add');

	};

	var start = function(){
		$('#btn-start').click(function() {
			var $initQuantityInput = $('#init-quantity');
			var startQuantity = parseInt($initQuantityInput.val());

			if (isNaN(startQuantity) || startQuantity <= 0) {
				alert('请输入正整数！');
				$initQuantityInput.val(null);
			}
			else {
				$initQuantityInput.parent('.form-group').slideUp('slow');

				Runloop.start(startQuantity, theCanvas, Mousemove);

				toggleBtn('#btn-pause');
				toggleBtn(this);
				toggleBtn('#btn-add');
			}
		});

		$('#btn-pause').click(function(){
			Runloop.pause();
			toggleBtn(this);
			toggleBtn('#btn-recover');
		});

		$('#btn-recover').click(function(){
			Runloop.recover();
			toggleBtn(this);
			toggleBtn('#btn-pause');
		});

		$('#btn-add').click(function(){
			var $addQuantityInput = $('#add-quantity');
			var addNum = parseInt( $addQuantityInput.val() );

			if( isNaN(addNum) || addNum <= 0){
				alert('请输入正整数！');
			}
			else{
				Runloop.addEntities(addNum);
			}

			$addQuantityInput.val(null);
		});

		$(theCanvas).on('mousedown', Mousemove.mouseDownListener);

	};

	var run = function(canvas){
		$(document).ready(function(){
			init(canvas);
			start();
		});
	};

	return {
		run: run
	};
});